<!-- 任务窗口 -->

<script setup lang="ts">
import { onMounted, ref, toRef } from 'vue';
import useApp from '@/store/useApp';
import { ElButton, ElCol, ElDrawer, ElEmpty, ElRow, ElSpace, ElTag } from 'element-plus';
import { saveAs } from "file-saver";
import JSZip from 'jszip';
import { useStorage } from '@vueuse/core';
import { findLastIndex } from 'lodash-es';

const storeApp = useApp();

const stateMap = {
    waiting: ["等待中", "info"],
    loading: ["下载中", "primary"],
    success: ["下载成功", 'success'],
    fail: ['下载失败', 'danger']
};


type TTask = {
    // 任务自定义ID
    tid?: any;
    state: "waiting" | "loading" | "success" | 'fail',
    title: string,
    data: [];
};

// 运行标识：true 可运行 ｜ 暂停运行
const flag = ref(true);
const taskStock = useStorage<TTask[]>("APP_TASK_LIST", []);
const running = toRef(storeApp, "taksIsRunning");

window.addEventListener("appTask", ({ detail }: any) => {
    const { title, data = [] } = detail;
    taskStock.value.unshift({
        state: "waiting",
        title,
        data
    });
    startTask();
});

const startTask = () => {
    if (!flag || running.value || taskStock.value.length == 0) return;
    const index = findLastIndex(taskStock.value, ['state', "waiting"]);
    createZip(index);
};

const downloadFile = async (url: string) => {
    // url = url.replace(/^https?:\/\/[^\/]+/, '');
    const response = await fetch(url);
    if (!response.ok) throw new Error(`Failed to fetch ${url}`);
    return await response.blob();
};

const createZip = async (index: number) => {
    const source = toRef(taskStock.value[index]);
    
    const { data, title = (+new Date()).toString() } = source.value;

    try {
        const zip = new JSZip();
        const folder = zip.folder(title);
        source.value.state = 'loading';

        for (let i = 0; i < data.length; i++) {
            const url = data[i] as string;
            const blob = await downloadFile(url);
            const fileName = url.split('/').pop() as string; // 从URL中提取文件名
            folder!.file(fileName, blob);
        }

        // 生成ZIP文件
        const content = await zip.generateAsync({ type: 'blob' });
        saveAs(content, `${title}.zip`); // 使用FileSaver.js触发下载
        source.value.state = 'success';
    } catch (err) {
        console.log("=errr", err);
        source.value.state = 'fail';
    } finally {
        // 做了一下延迟
        setTimeout(() => {
            running.value = false;
            startTask();
        }, 1000);
    }
};

onMounted(() => {
    // startTask();
});

// 清除已下载资源记录
const handleClearTask = (isAll?: boolean) => {
    if (isAll) {
        taskStock.value.length = 0;
    } else {
        const newList = taskStock.value.filter((e) => e.state !== 'success');
        taskStock.value = newList;
    }
};

// 暂停还没有下载的内容
// const pauseTask = () => {
//     flag.value = false;
// };

// const restartTask = () => {
//     flag.value = true;
//     startTask();
// };


// 重试
const handleRetry = (index: number) => {
    if (index == -1) {
        // 所有失败的重试
        taskStock.value = taskStock.value.map((e) => {
            if (e.state == 'fail') {
                e.state = 'waiting';
            }
            return e;
        });
    } else {
        // 指定重试
        taskStock.value[index].state = "waiting";
    }
    startTask();
};
</script>
<template>
    <ElDrawer v-model="storeApp.taskIsShow" title="任务进度" size="800px">
        <template #header>
            <div class="flex justify-between">
                <div class="font-bold text-lg">任务进度</div>

                <div>
                    <ElSpace>
                        <ElButton class="mr-3" text type="warning" @click="handleClearTask(true)">清除全部</ElButton>
                        <ElButton class="mr-3" text @click="handleClearTask()">清除已下载</ElButton>
                        <ElButton class="mr-3" text type="primary" @click="handleRetry(-1)">重试全部</ElButton>
                        <!-- <ElButton v-if="flag"
                                  class="mr-3" text @click="pauseTask">暂停任务</ElButton>
                        <ElButton v-else-if="!running"
                                  class="mr-3" text @click="restartTask">开始任务</ElButton> -->
                    </ElSpace>
                </div>
            </div>
        </template>

        <ElRow :gutter="16">
            <ElCol :span="2">序号</ElCol>
            <ElCol :span="16">标题</ElCol>
            <ElCol :span="3">状态</ElCol>
            <ElCol :span="3">操作</ElCol>
        </ElRow>

        <ElEmpty v-if="taskStock.length == 0" title="暂无任务" />

        <template v-for="(item, index) in taskStock" :key="index">
            <ElRow class="mt-3" :gutter="16">
                <ElCol :span="2">{{ index + 1 }}</ElCol>

                <ElCol :span="16">
                    {{ item.title }}
                </ElCol>
                <ElCol :span="3">
                    <ElTag :type="stateMap[item.state][1]">
                        {{ stateMap[item.state][0] }}
                    </ElTag>
                </ElCol>
                <ElCol :span="3">
                    <ElButton type="primary" v-if="item.state == 'fail'" @click="handleRetry(index)">重试</ElButton>
                </ElCol>
            </ElRow>
        </template>
    </ElDrawer>
</template>